<template>
  <ul class="list">
    <li
      class="item"
      v-for="item of letter"
      :key="item"
      :ref="item"
      @touchstart="handletouchstart"
      @touchmove="handletouchmove"
      @touchend="handletouchend"
      @click="handleClick"
    >{{item}}</li>
  </ul>
</template>

<script>
export default {
  name: "CityAlpha",
  data() {
    return {
      touchStatus: false,
      startY: "",
      timer: null
    };
  },
  update() {
    this.startY = this.$refs["A"][0].offsetTop
  },
  props: {
    city: Array
  },
  computed: {
    letter() {
      const letter = [];
      for (let i of this.city) {
        letter.push(i.title)
      }
      return letter
    }
  },
  methods: {
    handleClick(e) {
      this.$emit("change", e.target.innerHTML);
    },
    handletouchstart(e) {
      this.touchStatus = true
    },
    handletouchmove(e) {
      if (this.touchStatus) {
        if (this.timer) {
          // 函数节流，节约函数执行频率，提高网页型性能
          clearTimeout(this.timer)
        }
        this.timer = setTimeout(() => {
          const endY = e.touches[0].clientY
          // 此处startY定义为固定变量，防止方法运行后一直重复获取，提高性能
          const index = Math.floor((endY - this.startY) / 20)
          if (index >= 0 && index < this.letter.length) {
            this.$emit("change", this.letter[index])
          }
        }, 16);
      }
    },
    handletouchend(e) {
      this.touchStatus = false
    }
  }
};
</script>

<style lang="stylus" scoped>
@import '~styles/variavle.styl'
* 
  font-size 0.3rem
  margin 0
  padding 0
ul li 
  list-style none
.list
  position absolute
  top 1.4rem
  right 0
  bottom 0
  display flex
  flex-direction column
  justify-content center
  width 0.4rem
  .item 
    inline-height 0.4rem
    text-align center
    color $bgColor
</style>
